#include <sstream>
#include "core.cpp"

#define IMAGECOUNT 2
#define FOLDER "images/"
#define PREFIX "img"
#define EXT ".jpg"

int main(int argc, char **argv)
{
  IplImage *img,*binary;
  stringstream ss;

  cvNamedWindow("Source", CV_WINDOW_AUTOSIZE); 
  cvMoveWindow("Source", 100, 100);
  cvNamedWindow("Final", CV_WINDOW_AUTOSIZE); 
  cvMoveWindow("Final", 500, 100);
  
  int count=1;
  
  for(int i=1;i<=IMAGECOUNT;i++)
  {    
    char s[20];
    sprintf(s,"images/img%d.jpg",i);
    img = cvLoadImage(s);
    
    if(!img){
      printf("Could not load image file\n");
      exit(0);
    }
    
    binary = cvCreateImage(cvGetSize(img),8,1);
    getBinary(img,binary);
    
    IplImage* binary1 = cvCreateImage(cvGetSize(img),8,1);
    thinChars(binary,2);
    cvCopy(binary, binary1);
    
    CvMemStorage* storage = cvCreateMemStorage(0);
    CvSeq* contour = 0;
    cvFindContours(binary, storage, &contour, sizeof(CvContour), CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE );
    CvRect rect;

    cvShowImage("Final",binary1);
    for( ; contour != 0; contour = contour->h_next )
    {
      rect = cvBoundingRect(contour,0);
      cvSetImageROI(binary1,rect);
      char file[20];
      sprintf(file,"test%d.jpg",count);
      cvSaveImage(file, binary1);
      cvResetImageROI(binary1);
      cvRectangle(img,cvPoint(rect.x,rect.y),cvPoint(rect.x+rect.width,rect.x+rect.height),cvScalar(255));
      cvShowImage("Source",img);
      cvWaitKey(0);
      count++;
    }
    cvReleaseImage(&binary);
    cvReleaseImage(&binary1);
  }
}